/**
 * www.easyplatform.cn ©2016
 */
package cn.easyplatform.studio.web.views.impl;

import cn.easyplatform.studio.StudioApp;
import cn.easyplatform.studio.cmd.entity.QueryModelCmd;
import cn.easyplatform.studio.vos.EntityVo;
import cn.easyplatform.studio.web.editors.EditorCallback;
import cn.easyplatform.type.EntityType;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.*;

import java.util.List;

/**
 * @author <a href="mailto:shiny_vc@163.com">陈云亮</a> <br/>
 * @since 2.0.0 <br/>
 */
public class DatasourceView extends AbstractView<String> {

	private Grid grid;

	/**
	 * @param cb
	 */
	protected DatasourceView(EditorCallback<String> cb, Component component) {
		super(component, cb);
	}

	@Override
	protected void createContent(Component parent) {
		// 内容
		grid = new Grid();
		grid.setHflex("1");
		grid.setVflex("1");
		grid.setId("datasourceView_grid_result");
		Columns columns = new Columns();
		columns.setSizable(true);
		Column column = new Column(Labels.getLabel("entity.id"));
		column.setWidth("200px");
		column.setParent(columns);

		column = new Column(Labels.getLabel("entity.name"));
		column.setWidth("200px");
		column.setParent(columns);

		column = new Column(Labels.getLabel("entity.desp"));
		column.setHflex("1");
		column.setParent(columns);

		columns.setParent(grid);
		grid.appendChild(new Rows());
		grid.setParent(parent);
		List<EntityVo> data = StudioApp.execute(grid, new QueryModelCmd(
				EntityType.DATASOURCE.getName()));
		if (data != null)
			redraw(data);
	}

	private void redraw(List<EntityVo> data) {
		for (EntityVo vo : data) {
			Row row = new Row();
			row.setSclass("epstudio-link");
			row.setValue(vo);
			row.appendChild(new Label(vo.getId()));
			row.appendChild(new Label(vo.getName()));
			row.appendChild(new Label(vo.getDesp()));
			row.setParent(grid.getRows());
			row.addEventListener(Events.ON_DOUBLE_CLICK, this);
		}
	}

	public void onEvent(Event event) throws Exception {
		Row row = (Row) event.getTarget();
		EntityVo vo = row.getValue();
		cb.setValue(vo.getId());
		grid.getRoot().detach();
		onCloseClick(win);
	}
}
